#!/bin/sh

#--------------------------------------------------------------------
# General Variables
#--------------------------------------------------------------------

_W_DEVICE=${_W_DEVICE:-en0}

#--------------------------------------------------------------------
# General Utilities
#--------------------------------------------------------------------

case "$fn" in

    # Install macOS software updates, update installed Ruby gems, Homebrew, npm, pip and their installed packages
    "update")

        echo "Updating macOS..."
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}sudo softwareupdate -i -a;\n${NC}"
        fi
        sudo softwareupdate -i -a;

        echo "Updating Homebrew and its installed packages..."
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}brew update; brew upgrade;  brew upgrade --cask; brew cleanup; \n${NC}"
        fi
        brew update; brew upgrade;  brew upgrade --cask; brew cleanup;

        echo "Updating npm and its installed packages..."
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}npm install npm -g; npm update -g;\n${NC}"
        fi
        npm install npm -g; npm update -g;

        echo "Updating Yarn's installed packages..."
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}yarn global upgrade;\n${NC}"
        fi
        yarn global upgrade;

        echo "Updating installed Ruby gems..."
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}sudo gem update --system; sudo gem update\n${NC}"
        fi
        sudo gem update --system; sudo gem update

        echo "Updating installed pip packages..."
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}pip list --outdated --format=freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U\n${NC}"
        fi
        pip list --outdated --format=freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U

        if [ -x "$(command -v pip3)" ]; then
            echo "Updating installed pip3 packages..."
            if [ "$echocommand" == "true" ]; then
                echo "${GREEN}pip3 list --outdated --format=freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip3 install -U\n${NC}"
            fi
            pip3 list --outdated --format=freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip3 install -U
        fi

        if [ -f /usr/local/bin/apm ]; then
            echo "Updating Atom Packages..."
            if [ "$echocommand" == "true" ]; then
                echo "${GREEN}apm upgrade --no-confirm\n${NC}"
            fi
            apm upgrade --no-confirm
        fi
    ;;


    # Upgrade Mac CLI to the latest version
    "upgrade")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}sh -c "$(curl -fsSL https://raw.githubusercontent.com/guarinogabriel/mac-cli/master/mac-cli/tools/update)"\n\n${NC}"
        fi
        sh -c "$(curl -fsSL https://raw.githubusercontent.com/guarinogabriel/mac-cli/master/mac-cli/tools/update)"
    ;;


    # Uninstall Mac CLI from your Mac
    "uninstall")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}sh -c "$(curl -fsSL https://raw.githubusercontent.com/guarinogabriel/mac-cli/master/mac-cli/tools/uninstall)"\n\n${NC}"
        fi
        sh -c "$(curl -fsSL https://raw.githubusercontent.com/guarinogabriel/mac-cli/master/mac-cli/tools/uninstall)"
    ;;


    # Get macOS Info
    "info")
        printf "${GREEN}sw_vers\n${NC}"
        sw_vers
    ;;


    # Lock Mac
    "lock")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend\n\n${NC}"
        fi
        /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend
    ;;


    # Restart Mac
    "restart")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}osascript -e 'tell app 'loginwindow' to «event aevtrrst»''\n\n${NC}"
        fi
        osascript -e 'tell app "loginwindow" to «event aevtrrst»'
    ;;


    # Sleep
    "sleep")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}pmset sleepnow\n\n${NC}"
        fi
        pmset sleepnow
    ;;


    # Shutdown Mac
    "shutdown")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}osascript -e 'tell app 'loginwindow' to «event aevtrsdn»'\n\n${NC}"
        fi
        osascript -e 'tell app "loginwindow" to «event aevtrsdn»'
    ;;

    # Uptime
    "uptime")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}uptime\n\n${NC}"
        fi
        uptime
    ;;


    #List folders in current directory
    "folders:list")
        du -sk * | sort -rn
    ;;


    # Calculate folder size
    "folder:size")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}du -sh .\n\n${NC}"
        fi
        echo "Calculating folder size..."
        echo "Folder size:"
        du -sh .
    ;;


    # Show hidden files
    "hidden:show")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}defaults write com.apple.finder AppleShowAllFiles YES; killall Finder\n\n${NC}"
        fi
        defaults write com.apple.finder AppleShowAllFiles YES; killall Finder
    ;;


    # Hide hidden files
    "hidden:hide")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}defaults write com.apple.finder AppleShowAllFiles NO; killall Finder\n\n${NC}"
        fi
        defaults write com.apple.finder AppleShowAllFiles NO; killall Finder
    ;;


    # Check bluetooth status
    "bluetooth:status")
        defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState | \
            awk '{ if($1 != 0) {print "Bluetooth: ON"} else { print "Bluetooth: OFF" }  }'
    ;;


    # Enable bluetooth
    "bluetooth:enable")
        echo "${GREEN}Bluetooth enabled{NC}"
        sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1 && \
            sudo killall -HUP bluetoothd
    ;;


    # Disable bluetooth
    "bluetooth:disable")
        echo "${GREEN}Bluetooth disabled${NC}"
        sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0 && \
            sudo killall -HUP bluetoothd
    ;;


    # Check wifi status
    "wifi:status")
        /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I
    ;;


    # Check available wifi networks
    "wifi:scan")
        /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s
    ;;


    # Enable wifi
    "wifi:enable")
        echo "${GREEN}Wifi enabled${NC}"
        networksetup -setairportpower ${_W_DEVICE} on
    ;;


    # Disable wifi
    "wifi:disable")
        echo "${GREEN}Wifi disabled${NC}"
        networksetup -setairportpower ${_W_DEVICE} off
    ;;


    # Add blank space to the dock
    "dock:add-space")
        if [ ! -z "$firstParameter" -a "$firstParameter" != " " ]; then
          echo "${GREEN}Added $firstParameter new blank spaces to the dock${NC}"

          for i in `seq "$firstParameter"`; do
            defaults write com.apple.dock persistent-apps -array-add '{"tile-type"="spacer-tile";}'
          done
        else
          echo "${GREEN}Added new blank space to the dock${NC}"
          defaults write com.apple.dock persistent-apps -array-add '{"tile-type"="spacer-tile";}'
        fi

        killall Dock
    ;;


    # Start screensaver
    "screensaver")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}open -a ScreenSaverEngine\n\n${NC}"
        fi
        open -a ScreenSaverEngine
    ;;


    # Eject all mounted volumes and disk
    "eject-all")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}osascript -e 'tell application 'Finder' to eject (every disk whose ejectable is true)'\n\n${NC}"
        fi
        osascript -e 'tell application "Finder" to eject (every disk whose ejectable is true)'
    ;;


    # Get battery information
    "battery")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}pmset -g batt\n\n${NC}"
        fi
        pmset -g batt
    ;;


    # Find text in current directory
    "find:text")

        if [ ! -z "$allParameters" -a "$allParameters" != " " ]; then
            echo "Please enter the extension to search (i.e.: csv): "

            read extension

            if [ ! -z "$extension" -a "$extension" != " " ]; then

                if [ "$echocommand" == "true" ]; then
                    echo "${GREEN}find . -iname '*.${GRAY}${extension}${GREEN}' | xargs grep -in --color '${GRAY}${allParameters}${GREEN}'${NC}"
                fi
                echo "\nRecursively find '"$allParameters"' inside directory..."
                find . -iname "*.$extension" | xargs grep -in --color "$allParameters"

            else
                echo "Please introduce the extension of the files to search. E.g: csv"
            fi
        else
            echo "Please introduce text to search. E.g:"
            echo "mac find:text Sample Search Text"
        fi
    ;;


    # Find biggest files in current directory
    "find:biggest-files")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}find . -type f -print0 | xargs -0 du | sort -n | tail -10 | cut -f2 | xargs -I{} du -sh {}${NC}"
        fi
        find . -type f -print0 | xargs -0 du | sort -n | tail -10 | cut -f2 | xargs -I{} du -sh {}
    ;;


    # Find biggest directories in current directory
    "find:biggest-directories")
        if [ "$echocommand" == "true" ]; then
            echo "${GREEN}find . -type d -print0 | xargs -0 du | sort -n | tail -10 | cut -f2 | xargs -I{} du -sh {}${NC}"
        fi
        find . -type d -print0 | xargs -0 du | sort -n | tail -10 | cut -f2 | xargs -I{} du -sh {}
    ;;


    # Extract Zip file
    "zip:extract")

        if [ ! -z "$firstParameter" -a "$firstParameter" != " " ]; then
            if [ "$echocommand" == "true" ]; then
                echo "${GREEN}unzip ${GRAY}${firstParameter}\n\n${NC}"
            fi
            unzip $firstParameter
        else
            echo "Please specify the Zip file to extract."
            echo "E.g.: zip:extract sample_file.zip"
        fi
    ;;


    # Compress Gzip file
    "gzip:compress")

        if [ ! -z "$firstParameter" -a "$firstParameter" != " " ]; then
            if [ "$echocommand" == "true" ]; then
                echo "${GREEN}gzip ${GRAY}${firstParameter}\n\n${NC}"
            fi
            gzip $firstParameter
        else
            echo "Please specify the file to compress."
            echo "E.g.: gzip:compress sample_file"
        fi
    ;;


    # Extract Gzip file
    "gzip:extract")

        if [ ! -z "$firstParameter" -a "$firstParameter" != " " ]; then
            if [ "$echocommand" == "true" ]; then
                echo "${GREEN}gzip -d ${GRAY}${firstParameter}\n\n${NC}"
            fi
            gzip -d $firstParameter
        else
            echo "Please specify the Gzip file to extract."
            echo "E.g.: gzip:extract sample_file.gz"
        fi
    ;;


    # Extract tar file
    "tar:extract")

        if [ ! -z "$firstParameter" -a "$firstParameter" != " " ]; then
            if [ "$echocommand" == "true" ]; then
                echo "${GREEN}tar -xvzf ${GRAY}${firstParameter}\n\n${NC}"
            fi
            tar -xvzf $firstParameter
        else
            echo "Please specify the tar file to extract."
            echo "E.g.: tar:extract sample_file.tgz"
	    fi
    ;;


    # Compress file/folder using TAR with progress indicator
    "tar:compress")
        echo "Please enter the filename to save the .tgz file: "

        if [ ! -z "$firstParameter" -a "$firstParameter" != " " ]; then
            read filename

            if [ ! -z "$filename" -a "$filename" != " " ]; then
                if [ "$echocommand" == "true" ]; then
                    echo "${GREEN}tar -czf${GRAY}: ${firstParameter}${GREEN}  | (pv -p --timer --rate --bytes > '${GRAY}${filename}${GREEN}'.tgz)\n\n${NC}"
                fi
                tar -czf - $firstParameter | (pv -p --timer --rate --bytes > "$filename".tgz)
            else
                "Please specify the file name"
            fi
        else
            echo "Please specify the folder or directory to compress."
            echo "E.g.: tar:compress foldername"
        fi
    ;;


    # Search and replace string on file
    "search:replace")
        echo "Please enter the string to search on the file:"

        if [ ! -z "$firstParameter" -a "$firstParameter" != " " ]; then
            read searchString

            if [ ! -z "$searchString" -a "$searchString" != " " ]; then

                echo "Please enter the string that will replace the search string:"
                read replaceString

                if [ ! -z "$replaceString" -a "$replaceString" != " " ]; then

                    if [ "$echocommand" == "true" ]; then
                        echo "${GREEN}LC_CTYPE=C sed -i'' -e 's#${GRAY}${searchString}${GREEN}#${GRAY}${replaceString}${GREEN}#g' ${GRAY}${firstParameter}\n\n${NC}"
                    fi
                    LC_CTYPE=C sed -i'' -e 's#'"${searchString}"'#'"${replaceString}"'#g' $firstParameter

                else
                    "Please specify the string to replace"
                fi

            else
                "Please specify the string to search"
            fi
        else
            echo "Please specify the file to perform the search and replace operation"
            echo "E.g.: search:replace /path/to/file.csv"
        fi
    ;;


esac
